<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>ajax封装</title>
</head>
<body>
	<script>
		// 封装ajax
		ajax({
			type:'get',
			url:'http:durobot.baidu.com',
			data:"name=zhangsan&age=lisi",
			contentType:"application/x-www-form-urlencoded",
			success:function(res){
				console.log(res)
			},
			error:function(err){
				console.log(err)
			}

		});

		function ajax(options) {
			var defaults = {
				type:'get',
			    url:'',
			    data:{},
	            contentType:"application/json",
			    success:function(res){},
			    error:function(err){}
			}
			Object.assign(defaults,options)

			let xhr = new XMLHttpRequest();
			var params = "";
			var url =defaults.url;

			if (typeof defaults.data=="string") {
				params = defaults.data
			}else{
				for(let item in defaults.data){
					params += item + "=" defaults.data[item] + "&";
				}
				params = params.substr(0,params.length-1)
			}

			if (defaults.type=="get") {
				//readyStates:0
				url = url +"?" +params
			    xhr.open(defaults.type,url);
			}else{
				//readyStates:0
			    xhr.open(defaults.type,url);
			}
			if (defaults.type=="get") {		
			   //readySates:1
			   xhr.send();

			}else{
			   let contentType = defaults[contentType];
			   if (contentType == "application/json") {
			       //readySates:1
			       xhr.send(JSON.stringify(params));
			   }else{
			   	     xhr.send(params);
			   }
			   
			}
			//readySates:2
			//接受到部分数据readySattes:3
			xhr.onreadyStateChange = function(){
				//接受到全部数据readySattes:4
				if (xhr.status==200 && xhr.readySate ==4) {
					let responseText=xhr.responseText;
					let responseContentType = xhr.getReoponseHeader['content-type'];
					if (responseContentType.includes("application/json")) {	
						responseText = JSON.parse(responseText)
					}
					defaults.success(xhr.responseText)
				}else{
					var err = {
						status:xhr.status,
						msg:"ajax发生错误"
					}
					defaults.error(err)
				}
			}


		}
		



	</script>
	
</body>
</html>